package cn.com.demo.service;

import cn.com.demo.config.MyUser;
import cn.com.demo.dao.RolePermissionDao;
import cn.com.demo.dao.UserInfoDao;
import cn.com.demo.entity.UserInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private RolePermissionDao rolePermissionDao;
    /**
     * 按需决定是否需要引入密码加密
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
     */
    @Override
    public UserDetails loadUserByUsername(String usename) throws UsernameNotFoundException {
        // 查询数据库
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",usename);
        UserInfo userInfo = userInfoDao.selectOne(queryWrapper);
        if (userInfo ==null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 获取用户角色
        List<String> roles = rolePermissionDao.getRuleByUserId(userInfo.getId());
        // 获取用户权限(url)
        List<String> per = rolePermissionDao.getPermissByUserId(userInfo.getId());
        for (String role : roles) {
            per.add("ROLE_"+role);
        }
        List<GrantedAuthority> auths = new ArrayList<>();
        for (String s : per) {
            GrantedAuthority e = new SimpleGrantedAuthority(s);
            auths.add(e);
        }
        // 返回认证主体UserDetails
        return new MyUser(userInfo.getUsername(),userInfo.getPassword(),auths);
        //使用非自定义的密码，可能需要进行加密后再放置进认证主体密码属性中去
        // return new User(userInfo.getUsername(),bCryptPasswordEncoder.encode(userInfo.getPassword()),auths);
    }
}
